/*
 * @ : Copyright (c) 2021 Phytium Information Technology, Inc.
 *
 * SPDX-License-Identifier: Apache-2.0.
 *
 * @Date: 2021-04-27 13:52:41
 * @LastEditTime: 2021-07-30 14:45:40
 * @Description:  Description of file
 * @Modify History:
 * * * Ver   Who        Date         Changes
 * * ----- ------     --------    --------------------------------------
 */

#include "ft_can_hw.h"
#include "ft_can.h"
#include "parameters.h"
#include "ft_assert.h"
#include "ft_debug.h"

#define CAN_HW_DEBUG_TAG "CAN_HW"

#define CAN_HW_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(CAN_HW_DEBUG_TAG, format, ##__VA_ARGS__)
#define CAN_HW_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(CAN_HW_DEBUG_TAG, format, ##__VA_ARGS__)
#define CAN_HW_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(CAN_HW_DEBUG_TAG, format, ##__VA_ARGS__)

void FCanReset(FCan *instance_p)
{
    u32 reg_value;
    FCanConfig *config_p;
    FT_ASSERTVOID(instance_p != NULL);
    FT_ASSERTVOID(instance_p->is_ready == FT_COMPONENT_IS_READY);
    config_p = &instance_p->config;

    reg_value = FCAN_READREG(config_p->base_address, FCAN_CTRL_OFFSET);
    if (reg_value & FCAN_CTRL_XFER_MASK)
    {
        CAN_HW_DEBUG_E("FT can is not in configration mode\n");
        FT_ASSERTVOID(0);
        return;
    }

    /* reset can */
    FCAN_WRITEREG(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_RST_MASK);

    /* Identifier mask enable */
    FCAN_SETBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_AIME_MASK);
    FCAN_WRITEREG(config_p->base_address, FCAN_ACC_ID0_MASK_OFFSET, FCAN_ACC_IDN_MASK);
    FCAN_WRITEREG(config_p->base_address, FCAN_ACC_ID1_MASK_OFFSET, FCAN_ACC_IDN_MASK);
    FCAN_WRITEREG(config_p->base_address, FCAN_ACC_ID2_MASK_OFFSET, FCAN_ACC_IDN_MASK);
    FCAN_WRITEREG(config_p->base_address, FCAN_ACC_ID3_MASK_OFFSET, FCAN_ACC_IDN_MASK);

    FCAN_CLEARBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_RST_MASK);

    /* Enable interrupts */
    FCAN_WRITEREG(config_p->base_address, FCAN_INTR_OFFSET, FCAN_INTR_TEIE_MASK | FCAN_INTR_REIE_MASK);

    /* canfd config  */

    if (instance_p->use_canfd)
    {
        CAN_HW_DEBUG_I("can fd is go to \r\n");
        FCAN_SETBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_FDCRC_MASK | FCAN_CTRL_IOF_MASK);
    }
}
